<template>
  <div class="login_container">
    <div class="login_box">
      <!-- 1-登录表单区域 -->
      <el-form :rules="loginFormRules" ref="loginFormRef" label-width="0px" class="login_form" :model="loginForm">
        <h1 class="lg-title">十六号会员管理系统</h1>
        <!-- 用户名输入框 -->
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" v-model="loginForm.username"></el-input>
        </el-form-item>
        <!-- 密码输入框 -->
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" type="password" v-model="loginForm.password" show-password></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="resetLoginForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import {
    login,
    getUserInfo
  } from "@/api/login";

  export default {
    data() {
      return {
        // 登录表单的数据绑定对象
        loginForm: {
          username: "",
          password: ""
        },
        //   表单的验证规则对象
        loginFormRules: {
          //   验证用户名和密码是否合法
          username: [{
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          }],
          password: [{
            required: true,
            message: "请输入密码",
            trigger: "blur"
          }]
        }
      };
    },
    methods: {
      //   点击重置按钮，重置登录表单
      resetLoginForm() {
        this.$refs.loginFormRef.resetFields();
      },

      // 登录，调用接口
      login() {
        this.$refs.loginFormRef.validate(async valid => {
          if (valid) {
            // 调用接口
            login(this.loginForm.username, this.loginForm.password)
              .then(res => {
                // console.log(res.data);
                localStorage.setItem('vue-msm-token', res.data.data.token)
                // 如果验证通过 res.data.flag为true
                getUserInfo(res.data.token).then(res => {
                  // console.log(JSON.stringify(res.data.data));
                  localStorage.setItem('vue-msm-user', JSON.stringify(res.data.data))
                  // 去首页
                  this.$router.push('/')
                })

              })
          }
        });
      }
    }
  };
</script>

<style lang="less" scoped>
  .login_container {
    background-color: #2b4b6b;
    background-image: url("../../assets/login_bg.png");
    background-size: 100%;
    height: 100%;
  }

  .login_box {
    width: 450px;
    height: 300px;
    background-color: #fff;
    border-radius: 3px;
    opacity: 0.85;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .lg-title {
    text-align: center;
  }

  .login_form {
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
    position: absolute;
    bottom: 0;
  }

  .btns {
    display: flex;
    justify-content: flex-end;
  }
</style>